//
//  MyOrderViewController.m
//  HMShoperApp
//
//  Created by chirui on 2018/6/20.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "MyOrderViewController.h"
#import "HTHorizontalSelectionList.h"
#import "OrderTableViewCell.h"
#import "SellOrderDetailsViewController.h"
#import "SellOrderFinishDetailsViewController.h"
#import "LogingViewController.h"

@interface MyOrderViewController ()<HTHorizontalSelectionListDataSource,HTHorizontalSelectionListDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    
    //创建的ui
    UIScrollView * _topScrollView;
    UIScrollView * _scrollView;//内容上的滑块
    NSArray * _titileArray;
    UITableView * _tableView;
    CGPoint _point; //设置偏移量时使用
    int _totailPage;
    int _page;
    NSString * typeStr;
    UIView * noBodyView;
    NSMutableArray * allOrderArray;
    NSArray * statusArray;
    
}

@property(nonatomic,strong)HTHorizontalSelectionList * selectionList;
@property (nonatomic,strong) SZTextView * sztTextView;
@property(nonatomic,assign)NSInteger index;

@end

@implementation MyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    self.index = 0;
    _page =1;
    typeStr = [NSString stringWithFormat:@"%ld",self.index];
    allOrderArray = @[].mutableCopy;
    
    
    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关内容！" onView:nil];
    
    
    self.view.userInteractionEnabled=YES;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.navigationItem.titleView=[TopLabel withLabelWithLabelText:@"我的订单"];
    
    
    _titileArray =@[@"待配送",@"配送中",@"已完成"];
    statusArray = @[@"wait",@"deliver",@"done"];
    
    typeStr = statusArray[self.index];
    [self creatUI];
    [self requestDataForNet]; // 拉取全部数据
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//第三方库的使用

-(void)creatUI{
    //标题的ScrollView
    
    self.edgesForExtendedLayout =UIRectEdgeNone;
    
    _selectionList =[[HTHorizontalSelectionList alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    _selectionList.dataSource=self;
    _selectionList.delegate=self;
    [self.view addSubview:_selectionList];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:17] forState:UIControlStateSelected];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:16] forState:UIControlStateNormal];
    [_selectionList setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_selectionList setTitleColor:NavBackColor forState:UIControlStateSelected];
    //设置button之间的间距
    float WidthBtnFloat;
    if (ISP4||ISP5) {
        WidthBtnFloat =15;
    }else if (ISP6){
        WidthBtnFloat =25;
    }else {
        WidthBtnFloat =30;
    }
    UIView * line =[[UIView alloc]initWithFrame:CGRectMake(0, 49, WIDTH, 1)];
    line.backgroundColor =Color(248, 248, 248);
    [_selectionList addSubview:line];
    _selectionList.buttonInsets= UIEdgeInsetsMake(5,WidthBtnFloat, 5, WidthBtnFloat);
    //滑动按钮下边的滑块设置
    _selectionList.selectionIndicatorColor = NavBackColor;
    _selectionList.selectionIndicatorHeight =3;
    _selectionList.bottomTrimColor =[UIColor whiteColor];
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake( 0, 50,WIDTH, HEIGHT- SH_TopHeight-SH_TabBarHeight-50) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:@"OrderTableViewCell" bundle:nil] forCellReuseIdentifier:[OrderTableViewCell reuseIdentifier]];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page =1;
        [self requestDataForNet];
        
    }];
    _tableView.mj_header =header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        
        [self requestDataForNet];
        
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    _tableView.mj_footer.hidden = YES;
    
}

#pragma mark------HTHorizontalSelectionListDelegate实现--
//点击效果
-(void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{
    
    typeStr = [NSString stringWithFormat:@"%ld",index];
    
    typeStr = statusArray[index];
    NSLog(@"typeStr === %@",typeStr);
    _page =1;
    
    
    [self requestDataForNet];
    [UIView animateWithDuration:0.6 animations:^{
        
        _scrollView.contentOffset =CGPointMake(WIDTH * index, 0);
    }];
    UITableView *tableViwe=(id)[self.view viewWithTag:1000+index];
    [tableViwe reloadData];
    
}
//返回下表对应的文字按钮
-(NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index{
    
    return _titileArray[index];
}
//多少个
-(NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList{
    
    return _titileArray.count;
    
}

#pragma mark------tableViewdelegate----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return allOrderArray.count;
   
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSDictionary * allDic = allOrderArray[section];
    NSArray * array = allDic[@"products"];
    return array.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSDictionary * allDic = allOrderArray[indexPath.section];

    NSArray * array = allDic[@"products"];
    NSDictionary * dic = array[indexPath.row];
    
    OrderTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[OrderTableViewCell reuseIdentifier] forIndexPath:indexPath];
    
    [cell.goodsImage sd_setImageWithURL:ImageUrl(dic[@"cover_photo"]) placeholderImage:ImageName(@"")];
    cell.goodsName.text = dic[@"product_name"];
    cell.goodsName.frame = CGRectMake(98, 10, WIDTH -160, 20);
    cell.goodsName.numberOfLines = 2;
    [cell.goodsName sizeToFit];
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"price"]];
    cell.numberLabel.text = [NSString stringWithFormat:@"X%@",dic[@"number"]];
//    cell.guigeLabel.text = [NSString stringWithFormat:@"%@",dic[@"option_name"]];
//
    cell.numberLabel.frame = CGRectMake(WIDTH-50, 10, 40, 20);
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 90;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * heardView =[[UIView alloc]initWithFrame:CGRectMake(0, 0,WIDTH,90)];
    heardView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    
    UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, WIDTH, 90)];
    bgView.backgroundColor = [UIColor whiteColor];
    
    [heardView addSubview:bgView];
    NSDictionary * dataDic = allOrderArray[section];

    NSDictionary * dic = dataDic;
    
    
    UILabel * shopName =[[UILabel alloc]initWithFrame:CGRectMake(10, 15, WIDTH - 150, 20)];
    shopName.font =[UIFont systemFontOfSize:16];
     shopName.textColor = [UIColor grayColor];
    shopName.text = [NSString stringWithFormat:@"订单编号：%@",dic[@"order_sn"]];
    [bgView addSubview:shopName];
    
    UILabel * timeLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 50, WIDTH - 120, 20)];
    timeLabel.font =[UIFont systemFontOfSize:16];
    timeLabel.textColor = [UIColor grayColor];
    timeLabel.text = [NSString stringWithFormat:@"变更时间：%@",dic[@"update_time"]];
    [bgView addSubview:timeLabel];
    
    UILabel * type =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH-110, 35, 100, 20)];
    type.font =[UIFont systemFontOfSize:16];
    
    type.textColor = [UIColor grayColor];
    type.textAlignment = NSTextAlignmentRight;
    type.text = dic[@"status_dict"];
    [bgView addSubview:type];
    return heardView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView * footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0,WIDTH,90)];
    footerView.backgroundColor =[UIColor whiteColor];
    
    NSDictionary * dataDic = allOrderArray[section];

    NSDictionary * dic = dataDic;
    
    
    UILabel * price =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH-160,10,150 , 20)];
    price.font =[UIFont systemFontOfSize:15];
    price.textAlignment = NSTextAlignmentRight;

    price.text = [NSString stringWithFormat:@"合计:￥%@",dic[@"order_price"]];
    [footerView addSubview:price];
    
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 45, WIDTH, 45)];
    view.backgroundColor =[UIColor whiteColor];
    [footerView addSubview:view];
    
    if ([dic[@"status"] isEqualToString:@"wait"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-180,15/2, 80, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:)andBtnTag:section  onView:view];
        
        [self creatRedBtnFrame:CGRectMake(WIDTH-90,15/2, 80, 30) andTitleStr:@"开始配送" andSel:@selector(cannleOrderBtn:) andBtnTag:section onView:view];
    }

    if ([dic[@"status"] isEqualToString:@"deliver"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-90,15/2, 80, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:)andBtnTag:section  onView:view];
    
    }
 
    if ([dic[@"status"] isEqualToString:@"done"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-90,15/2, 80, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:) andBtnTag:section onView:view];

    }
 
    
    return footerView;
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    //    ChangeOrderDetalViewController * changeOrder =[[ChangeOrderDetalViewController alloc]init];
    //    changeOrder.orderSnStr = dic[@"order_sn"];
    //    [self.navigationController pushViewController:changeOrder animated:NO];
    
    
}
#pragma mark 订单操作



-(void)lookMessageBtn:(UIButton *)btn{
    
    NSDictionary * dataDic = allOrderArray[btn.tag];
    
    [self getOrderDetailsFor:dataDic[@"order_id"]];
    NSLog(@"lookMessageBtn");
}


-(void)cannleOrderBtn:(UIButton *)btn {
    
    
    NSDictionary * dataDic = allOrderArray[btn.tag];
    
    NSDictionary * dic = dataDic;
    
    [self cancelOrderStatisForStr:dic[@"order_id"]];
}

/**
 *  封装边框按钮
 */
-(void)creatBoardBtnFrame:(CGRect)rec andTitleSte:(NSString *)title andSEL:(SEL)Click andBtnTag:
(NSInteger)tag onView:(UIView *)view {
    
    UIButton * deleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    deleBtn.frame = rec;
    deleBtn.backgroundColor =[UIColor whiteColor];
    [deleBtn setTitle:title forState:UIControlStateNormal];
    [deleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    deleBtn.layer.cornerRadius =15.f;
    deleBtn.layer.masksToBounds =YES;
    deleBtn.layer.borderWidth = 0.5f;
    deleBtn.layer.borderColor = [UIColor blackColor].CGColor;
    deleBtn.tag = tag;
    deleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [deleBtn addTarget:self action:Click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:deleBtn];
    
}

-(void)creatRedBtnFrame:(CGRect)rec andTitleStr:(NSString *)title andSel:(SEL)click andBtnTag:
(NSInteger )tag onView:(UIView *)view {
    
    
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = rec;
    btn.backgroundColor =[UIColor whiteColor];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:NavBackColor forState:UIControlStateNormal];
    btn.layer.cornerRadius =15.f;
    btn.layer.masksToBounds =YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    btn.layer.borderWidth = 0.5f;
    btn.tag = tag ;
    btn.layer.borderColor = NavBackColor.CGColor;
    [btn addTarget:self action:click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
}

-(UIButton *)creatCommentBtnFrame:(CGRect)rec andTitleStr:(NSString *)title andSel:(SEL)click andBtnTag:
(NSInteger )tag onView:(UIView *)view {
    
    
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = rec;
    btn.backgroundColor =[UIColor whiteColor];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:NavBackColor forState:UIControlStateNormal];
    btn.layer.cornerRadius =15.f;
    btn.layer.masksToBounds =YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    btn.layer.borderWidth = 0.5f;
    btn.tag = tag ;
    btn.layer.borderColor = NavBackColor.CGColor;
    [btn addTarget:self action:click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    return btn;
    
}

#pragma mark ----内容关联滑块-----


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag ==10000) {
        if (buttonIndex==0) {
            
            [self requestDataForNet];
        }
    }
    
    
}

//获取我的订单
-(void)requestDataForNet {
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];

            return ;
        }
    }

    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,order_list_Api];

    NSString * pageStr = [NSString stringWithFormat:@"%d",_page];
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"page_num":@"10",
                           @"page":pageStr,
                           @"status":typeStr
                           };


    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {

        if ([responseObject[@"code"] intValue]==200) {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                _totailPage = [responseObject[@"datas"][@"total_page"] intValue];
                if (_page==1) {

                    if (allOrderArray) {

                        [allOrderArray removeAllObjects];
                    }
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {

                        [allOrderArray addObject: dic];
                    }
                }else {

                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {

                        [allOrderArray addObject: dic];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{


                    if (allOrderArray.count>0) {
                        noBodyView.hidden =YES;
                    }else {
                        _tableView.mj_footer.hidden = YES;
                        noBodyView.hidden =NO;

                        [self.view addSubview:noBodyView];
                    }
                    [_tableView.mj_header endRefreshing];
                    [_tableView.mj_footer endRefreshing];
                    [_tableView reloadData];
                });
            });

        } else {
            if ([responseObject[@"code"] intValue]==220) {
                
                LogingViewController * tabbar  =[[LogingViewController alloc]init];
                
                [UIApplication sharedApplication].keyWindow.rootViewController =tabbar;
                
            }else {
                
                SHuiMBhudTextTimeStr(responseObject[@"mark"]);
            }
        }

    } failed:^(NSError *error) {

        NSLog(@"ERROR ==%@",error);
        SHuiMBhudTextNetError;
    }];

    
}

/**
 *  取货
 *
 */
-(void)cancelOrderStatisForStr:(NSString *)Ordstr {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,gotFood_order_api];

    NSDictionary * dic = @{@"order_id":Ordstr,
                           @"token":USER_DEFAULTGet(@"token"),
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           };
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {

        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"开始配送成功！");
            _page = 1;
            [self requestDataForNet];

        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        NSLog(@"ERROR ==%@",error);
        SHuiMBhudTextNetError;
    }];
    
}


-(void)getOrderDetailsFor:(NSString *)str{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,get_orderInfo_api];

    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":str,

                           };

    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {

        if ([responseObject[@"code"] intValue]==200) {

                SellOrderDetailsViewController * details =[[SellOrderDetailsViewController alloc]init];
                details.dataDic = responseObject[@"datas"];
                details.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:details animated:YES];
         

        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        NSLog(@"ERROR ==%@",error);
        SHuiMBhudTextNetError;
    }];

}

@end
